<template>
  <a-modal
    :title="title"
    :width="600"
    :visible="visible"
    :confirmLoading="confirmLoading"
    @ok="handleOk"
    @cancel="handleCancel"
    cancelText="关闭"
  >
    <div>
      <a-form-model :model="model" :form="form" :rules="rules" ref="form">
        <a-space>
          用户：
          <m-select-multi-user
            style="width: 500px;"
            v-decorator="['userId', { rules: [{ required: true, message: '请选择员工' }] }]"
            :multiple="false"
            @submitSelect="userSelect"
            :disabled="false"
          />
        </a-space>
        <a-row style="margin-top: 20px;margin-left: -100px" :gutter="16">
          <a-col :span="24">
            <a-form-model-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="公司" prop="company">
              <j-dict-select-tag placeholder="请选择公司" v-model="model.company" dictCode="crm_company,name,id" />
            </a-form-model-item>
          </a-col>
        </a-row>
        <a-row style="margin-top: 20px" :gutter="16">
          <a-col :span="12">
            <a-form-model-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="车间" prop="workshop">
              <j-dict-select-tag placeholder="请选择车间" v-model="model.workshop" dictCode="workshop" />
            </a-form-model-item>
          </a-col>
          <a-col :span="12">
            <a-form-model-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="班次" prop="shift">
              <j-dict-select-tag placeholder="请选择班次" v-model="model.shift" dictCode="shift2" />
            </a-form-model-item>
          </a-col>
        </a-row>
        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-model-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="工序" prop="workingProcedure">
              <j-dict-select-tag
                placeholder="请选择工序"
                v-model="model.workingProcedure"
                dictCode="working_procedure"
                disabled
                @change="workingProcedureChange"
              />
            </a-form-model-item>
          </a-col>
          <a-col :span="12">
            <a-form-model-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="工种" prop="workType">
              <j-dict-select-tag placeholder="请选择工种" v-model="model.workType" dictCode="work_type" />
            </a-form-model-item>
          </a-col>
        </a-row>
        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-model-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="机台选择" prop="selectText">
              <a-space>
                <a-input placeholder="请选择" style="width:100%" readOnly v-model="selectText"></a-input>
                <a-button type="primary" icon="plus" size="small" @click="showModal(procedure)"></a-button>
              </a-space>
            </a-form-model-item>
          </a-col>
          <a-col :span="12">
            <a-form-model-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="锭数" prop="ingotsIds">
              <a-space>
                <a-input placeholder="请选择" style="width:100%" readOnly v-model="ingotsIds"></a-input>
                <a-button type="primary" icon="plus" size="small" @click="showDingModal(model.ingotsIds)"></a-button>
              </a-space>
            </a-form-model-item>
          </a-col>
        </a-row>
        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-model-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="考勤状态" prop="attendanceStatus">
              <j-dict-select-tag
                placeholder="请选择考勤状态"
                v-model="model.attendanceStatus"
                dictCode="attendance_status"
              />
            </a-form-model-item>
          </a-col>
          <a-col :span="12">
            <a-form-model-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="计划日期" prop="planTime">
              <a-date-picker
                v-model:value="planTimeData"
                style="width: 100%;"
                placeholder="选择日期"
                :allowClear="false"
                @change="onChangePlanTime"
              />
            </a-form-model-item>
          </a-col>
        </a-row>
        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-model-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="开始时间" prop="startTime">
              <a-date-picker
                show-time
                v-model:value="startTime"
                style="width: 100%;"
                placeholder="选择日期"
                :allowClear="false"
                @change="onChangeStartTime"
              />
            </a-form-model-item>
          </a-col>
          <a-col :span="12">
            <a-form-model-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="结束时间" prop="endTime">
              <a-date-picker
                show-time
                v-model:value="endTime"
                style="width: 100%;"
                placeholder="选择日期"
                :allowClear="false"
                @change="onChangeEndTime"
              />
            </a-form-model-item>
          </a-col>
        </a-row>
        <a-row v-if="shiftSecList.length == 2" :gutter="16">
          <a-col :span="12">
            <a-form-model-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="开始时间2" prop="startTime">
              <a-date-picker
                show-time
                v-model:value="startTime2"
                style="width: 100%;"
                placeholder="选择日期"
                :allowClear="false"
                @change="onChangeStartTime2"
              />
            </a-form-model-item>
          </a-col>
          <a-col :span="12">
            <a-form-model-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="结束时间2" prop="endTime">
              <a-date-picker
                show-time
                v-model:value="endTime2"
                style="width: 100%;"
                placeholder="选择日期"
                :allowClear="false"
                @change="onChangeEndTime2"
              />
            </a-form-model-item>
          </a-col>
        </a-row>
        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-model-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="备注" prop="remark">
              <a-input placeholder="请选择" style="width:240%" v-model="model.remark"></a-input>
            </a-form-model-item>
          </a-col>
        </a-row>
      </a-form-model>
    </div>
    <jitai-luotong-modal
      ref="luotongModal"
      @planChoseSubmit="planChoseSubmit"
      :planTimeJiTai="model.planTime"
      :workshopJiTai="model.workshop"
    ></jitai-luotong-modal>
    <dingshu-modal ref="dingshuModal" @btnSure="btnSure"></dingshu-modal>
  </a-modal>
</template>

<script>
import { JeecgListMixin } from '@/mixins/JeecgListMixin'
import MSelectMultiUser from './MSelectMultiUser'
import JitaiLuotongModal from './JitaiLuotongModal'
import { httpAction } from '@/api/manage'
import pick from 'lodash.pick'
import JEditor from '@/components/jeecg/JEditor'
import JSwitch from '@/components/jeecg/JSwitch'
import { getUser } from '@api/customApi'
import moment from 'moment'
import DingshuModal from './DingshuModal'
const path = '/crm_daily_plan_spun_yarn/crmDailyPlanSpunYarn'
export default {
  props: {
    selectQuery: Object,
    planTime: String,
    shiftSecList: Array
  },
  mixins: [JeecgListMixin],
  name: 'UserSelectModal',
  components: {
    JitaiLuotongModal,
    DingshuModal,
    MSelectMultiUser,
    JEditor,
    JSwitch
  },
  data() {
    return {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 6 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 18 }
      },
      ingotsIds: '',
      dataSource1: [],
      procedure: '7',
      startTime: null,
      startTime2: null,
      endTime: null,
      endTime2: null,
      planTimeData: moment(new Date()).format('YYYY-MM-DD'),
      userName: '',
      selectNumber: '1',
      title: '操作',
      visible: false,
      disable: true,
      model: {
        company: '',
        ingotsIds: '',
        workshop: '',
        workingProcedure: '',
        workType: '',
        attendanceStatus: '',
        remark: ''
      },
      selectText: '',
      confirmLoading: false,
      form: this.$form.createForm(this),
      url: {
        list: path + '/list',
        add: '/crm_scheduling_spooling/crmSchedulingSpooling/add'
        // edit: '/crm_scheduling_spooling/crmSchedulingSpooling/edit'
      }
    }
  },
  created() {},
  mounted() {},
  methods: {
    userSelect(e) {
      this.userInfo = e[0]
      this.model.realname = this.userInfo.realname
      this.model.userId = this.userInfo.id
      this.model.workNo = this.userInfo.workNo
      this.model.avatar = this.userInfo.avatar
      console.log(e)
    },
    onChangePlanTime(date, dateString) {
      // 只有当dateString不为空时才更新model.planTime
      if (dateString.trim() !== '') {
        // if(this.model.shift==1){}
        this.model.planTime = dateString
        this.startTime = dateString + ' 00:00:00'
        this.endTime = dateString + ' 12:00:00'
        this.model.startTime = dateString + ' 00:00:00'
        this.model.endTime = dateString + ' 12:00:00'
        this.startTime2 = dateString + ' 00:00:00'
        this.endTime2 = dateString + ' 12:00:00'
        this.model.startTime2 = dateString + ' 00:00:00'
        this.model.endTime2 = dateString + ' 12:00:00'
      }
    },
    onChangeStartTime(date, dateString) {
      this.model.startTime = dateString
    },
    onChangeEndTime(date, dateString) {
      this.model.endTime = dateString
    },
    onChangeStartTime2(date, dateString) {
      this.model.startTime2 = dateString
    },
    onChangeEndTime2(date, dateString) {
      this.model.endTime2 = dateString
    },
    workingProcedureChange(val) {
      if (val == 1) {
        this.procedure = '清花'
      } else if (val == 2) {
        this.procedure = '梳棉'
      } else if (val == 3) {
        this.procedure = '精梳'
      } else if (val == 4) {
        this.procedure = '并条'
      } else if (val == 5) {
        this.procedure = '粗纱'
      } else if (val == 6) {
        this.procedure = '细纱'
      } else if (val == 7) {
        this.procedure = '络筒'
      }
    },
    showModal(param) {
      if (this.procedure != null && this.procedure != '') {
        this.$refs.luotongModal.show(this.model.schedulingSpunYarnDevices, param, true)
      } else {
        this.$message.warning('请选择工序')
      }
    },
    planChoseSubmit(params, selectPlanData, choseNum) {
      console.log(selectPlanData)
      //选择的机台id
      selectPlanData.forEach(item => {
        item.deviceIds = item.deviceIds.join(',')
      })
      console.log(selectPlanData)
      this.model.schedulingSpunYarnDevices = selectPlanData
      this.model.deviceId = selectPlanData[0].deviceIds
      if (selectPlanData.length > 0) {
        this.selectText = '已选择：' + choseNum.length + '台'
        this.model.deviceNum = choseNum.length
      } else {
        this.selectText = ''
      }
    },
    showDingModal() {
      this.$refs.dingshuModal.show(this.model.ingotsIds, '', true)
    },
    btnSure(selectIds, selectString) {
      console.log(selectIds)
      console.log(selectString)
      this.model.ingotsIds = selectString
      console.log(this.model.ingotsIds)
      this.ingotsIds = this.findRanges(selectString)
    },
    add() {
      this.disable = false
      // this.model = Object.assign({}, )
      this.selectText = ''
      this.model.planTime = this.planTime
      this.model.workshop = this.selectQuery.workshop
      this.model.shift = this.selectQuery.shift
      this.model.company = this.selectQuery.company
      this.model.attendanceStatus = 1
      this.model.workType = 1
      this.model.workingProcedure = 7
      this.planTimeData = this.planTime
      if (this.shiftSecList.length == 1) {
        // 如果只查到一个班就把时间直接赋值
        this.model.startTime = this.shiftSecList[0].startTime
        this.startTime = this.shiftSecList[0].startTime
        this.model.endTime = this.shiftSecList[0].endTime
        this.endTime = this.shiftSecList[0].endTime
      } else if (this.shiftSecList.length == 2) {
        // 如果是两个班要把两个时间都拿出来
        this.model.startTime = this.shiftSecList[0].startTime
        this.startTime = this.shiftSecList[0].startTime
        this.model.endTime = this.shiftSecList[0].endTime
        this.endTime = this.shiftSecList[0].endTime
        this.model.startTime2 = this.shiftSecList[1].startTime
        this.startTime2 = this.shiftSecList[1].startTime
        this.model.endTime2 = this.shiftSecList[1].endTime
        this.endTime2 = this.shiftSecList[1].endTime
      }
      // if (this.selectQuery.shift == 1) {
      //   this.model.startTime = this.planTime + ' 00:00:00'
      //   this.startTime = this.planTime + ' 00:00:00'
      //   this.model.endTime = this.planTime + ' 12:00:00'
      //   this.endTime = this.planTime + ' 12:00:00'
      // } else if (this.selectQuery.shift == 2) {
      //   this.model.startTime = this.planTime + ' 12:00:00'
      //   this.startTime = this.planTime + ' 12:00:00'
      //   this.model.endTime =
      //     new Date(new Date(this.planTime).getTime() + 24 * 60 * 60 * 1000).toISOString().split('T')[0] + ' 00:00:00'
      //   this.endTime =
      //     new Date(new Date(this.planTime).getTime() + 24 * 60 * 60 * 1000).toISOString().split('T')[0] + ' 00:00:00'
      // } else {
      //   this.model.startTime = this.selectQuery.startTime
      //   this.startTime = this.selectQuery.startTime
      //   this.model.endTime = this.selectQuery.endTime
      //   this.endTime = this.selectQuery.endTime
      // }
      this.model.ingotsIds =
        '1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64'
      this.ingotsIds = this.findRanges(
        '1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64'
      )
      this.edit({}, 1)
    },
    edit(record, isEdit) {
      if (isEdit != 1) {
        this.model = Object.assign({}, record)
      }
      this.visible = true
    },
    close() {
      this.$emit('close')
      this.visible = false
      this.disable = true
      this.model.userId = ''
      this.selectText = ''
      this.model.company = ''
      this.model.workshop = ''
      this.model.shift = ''
      this.model.workingProcedure = ''
      this.model.workType = ''
      this.model.deviceId = ''
      this.model.ingotsIds = ''
      this.model.attendanceStatus = ''
      this.model.planTime = null
      this.model.startTime = null
      this.model.endTime = null
      this.model.remark = ''
      this.startTime = null
      this.endTime = null
      this.model.schedulingSpunYarnDevices = ''
      this.model.deviceId = ''
      this.model.deviceNum = null
      this.$refs.form.resetFields()
    },

    handleOk() {
      this.$refs.form.validate(valid => {
        if (valid) {
          this.confirmLoading = true
          let httpurl = ''
          let method = ''
          if (!this.model.id) {
            httpurl += this.url.add
            method = 'post'
          } else {
            httpurl += this.url.edit
            method = 'put'
          }
          // 只有一班的时候正常提交
          if (this.shiftSecList.length == 1) {
            let formData = Object.assign(this.model)
            console.log('formData', formData)
            //时间格式化
            httpAction(httpurl, formData, method)
              .then(res => {
                if (res.success) {
                  this.$message.success(res.message != '' ? res.message : '执行成功')
                  this.$emit('ok')
                } else {
                  this.$message.warning(res.message)
                }
              })
              .finally(() => {
                this.confirmLoading = false
                this.close()
              })
          }
          //如果是有两班则需操作一下提交数据，提交两次,将startTime2拆出来分两次提交
          else if (this.shiftSecList.length == 2) {
            let formData = Object.assign(this.model)
            let formData2 = formData
            formData2.startTime = formData2.startTime2
            formData2.endTime = formData2.endTime2
            let formArr = [formData, formData2]
            for (let i = 0; i < formArr.length; i++) {
              httpAction(httpurl, formArr[i], method)
                .then(res => {
                  if (res.success) {
                    this.$message.success(res.message != '' ? res.message : '执行成功')
                    this.$emit('ok')
                  } else {
                    this.$message.warning(res.message)
                  }
                })
                .finally(() => {
                  // 判断提交完了关闭窗口
                  if (i == formArr.length) {
                    this.confirmLoading = false
                    this.close()
                  }
                })
            }
          }
        } else {
          return false
        }
      })
    },
    onChangePage(e) {
      this.ipagination.current = e
      this.loadData()
    },
    handleCancel() {
      this.close()
    },
    findRanges(numbersStr) {
      let numbers = numbersStr.split(',').map(Number) // 将字符串转换为数字数组
      numbers = Array.from(new Set(numbers)).sort((a, b) => a - b) // 去重并排序

      let fullRange = Array.from({ length: 64 }, (_, i) => i + 1) // 完整的1到64的范围
      let missingNumbers = fullRange.filter(num => !numbers.includes(num)) // 找到缺失的数字

      if (missingNumbers.length === 0) {
        return '1~64'
      }

      let ranges = []
      let start = 1

      missingNumbers.forEach(missing => {
        if (start < missing) {
          let end = missing - 1
          ranges.push(`${start}~${end}`)
        }
        start = missing + 1
      })

      if (start <= 64) {
        ranges.push(`${start}~64`)
      }

      return ranges.join('；')
    }
  }
}
</script>

<style scoped></style>
